<template>
  <div class="contract-no">
    <a-card size="small">
      <template #title>
        <span class="text-title">合同编号</span>
      </template>
      <template #extra>
        <a-button type="primary" ghost @click="editContractNo"> 编辑 </a-button>
      </template>
      <a-form layout="vertical">
        <a-row :gutter="[12, 0]" style="width: 100%; margin-top: 12px">
          <template v-for="(item, index) of dataList" :key="index">
            <a-col v-if="item.type == 'date'" :xs="24" :sm="12" :xl="8">
              <a-row :gutter="0">
                <a-col :span="14">
                  <a-form-item>
                    <a-select
                      v-model:value="item.condition_date"
                      placeholder="日期显示"
                      :options="optionsInit.conditionDate"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="10">
                  <a-form-item>
                    <a-select
                      v-model:value="item.condition_time"
                      placeholder="日期起始"
                      :options="optionsInit.conditionTime"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col v-if="item.type == 'txt'" :xs="12" :sm="4">
              <a-form-item>
                <a-input
                  v-model:value="item.condition_txt"
                  placeholder="固定文本"
                />
              </a-form-item>
            </a-col>
            <a-col v-if="item.type == 'order'" :xs="24" :sm="12">
              <a-row :gutter="0">
                <a-col :span="12">
                  <a-form-item>
                    <a-select
                      v-model:value="item.condition_order"
                      placeholder="当天合同顺序计数"
                      :options="optionsInit.conditionOrder"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-tooltip>
                    <template #title>
                      为避免合同序号冲突，建议3位数以上
                    </template>
                    <a-form-item>
                      <a-input-number
                        style="width: 100%"
                        placeholder="位数"
                        v-model:value="item.condition_num"
                        :precision="0"
                        :formatter="(value) => `${value}位`"
                        :parser="(value) => value.replace('位', '')"
                        :min="1"
                      />
                    </a-form-item>
                  </a-tooltip>
                </a-col>
                <a-col :span="6">
                  <a-tooltip>
                    <template #title> 生成时起始序号 </template>
                    <a-form-item>
                      <a-input-number
                        style="width: 100%"
                        placeholder="起始序号"
                        v-model:value="item.condition_start"
                        :precision="0"
                        :min="0"
                        :max="Math.pow(10, Number(item.condition_num)) - 1"
                      />
                    </a-form-item>
                  </a-tooltip>
                </a-col>
              </a-row>
            </a-col>
          </template>
        </a-row>
      </a-form>

      <div class="mt-10">
        <span>预览：</span>
        <span class="text-success fw-bold">
          {{ getPreviewText() }}
        </span>
      </div>
    </a-card>
    <EditContractNo
      :visible="editCtNoVisible"
      :data="dataList"
      @cancel="editCtNoVisible = false"
      @success="handleEditContractNoSuccess"
    />
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, watch } from "@vue/runtime-core";
import EditContractNo from "./EditContractNo.vue";
import { Form } from "ant-design-vue";
import store from "../../../../store";
import moment from "moment";

const useForm = Form.useForm;

const DEFAULT_CN_LIST = [
  { type: "date", condition_date: "date_1", condition_time: "time_1" },
  { type: "txt", condition_txt: "固定文本" },
  {
    type: "order",
    condition_order: "order_1",
    condition_num: 3,
    condition_start: 0,
  },
];

export default defineComponent({
  props: {
    validateTrigger: {
      type: Number,
      default: 0,
    },
  },
  components: { EditContractNo },
  setup(props, { emit }) {
    const state = reactive({
      optionsInit: {},
      editCtNoVisible: false,
      dataList: [],
    });

    /** 编辑合同编号 */
    const editContractNo = () => {
      state.editCtNoVisible = true;
    };

    /** 编辑合同编号保存 */
    const handleEditContractNoSuccess = (list) => {
      state.dataList = list;
      state.editCtNoVisible = false;
    };

    /** 获取预览文字 */
    const getPreviewText = () => {
      let text = "";
      state.dataList.forEach((item) => {
        if (item.type == "date") {
          text += getDateText(item);
        } else if (item.type == "txt") {
          text += item.condition_txt;
        } else if (item.type == "order") {
          text += getOrderText(item);
        }
      });
      return text;
    };
    // 获取日期预览文字
    const getDateText = (item) => {
      let dateStr = "";
      const today = moment();
      switch (item.condition_date) {
        case "date_1":
          // 年月
          dateStr = today.format("YYYYMM");
          break;
        case "date_2":
          // 年月日
          dateStr = today.format("YYYYMMDD");
          break;
        case "date_3":
          // 年-月
          dateStr = today.format("YYYY-MM");
          break;
        case "date_4":
          // 年-月-日
          dateStr = today.format("YYYY-MM-DD");
          break;
      }
      return dateStr;
    };
    // 获取序号预览文字
    const getOrderText = (item) => {
      let orderStr = "";
      if (item.condition_num) {
        orderStr = item.condition_start ? Number(item.condition_start) : 1;
        const needLen = Number(item.condition_num) - String(orderStr).length;
        for (let i = 0; i < needLen; i++) {
          orderStr = "0" + orderStr;
        }
      }
      return orderStr;
    };

    /** 表单 预留，不一定用到*/
    const modelRef = reactive({});
    const requiredRule = [{ required: true, message: "必填" }];
    const rulesRef = reactive({});
    const { validate, validateInfos } = useForm(modelRef, rulesRef);

    const validateForm = () => {
      emit("getResult", {
        params: {
          number_rule: state.dataList,
        },
        type: "ContractNo",
      });
    };

    watch(
      () => props.validateTrigger,
      () => {
        validateForm();
      }
    );

    /** 初始化 */
    const init = () => {
      store.dispatch("GetTemplateInit").then((initData) => {
        state.optionsInit = initData;
        const detail = store.getters.currentContractTpl;
        if (detail.id) {
          state.dataList = detail.number_rule;
        } else {
          state.dataList = JSON.parse(JSON.stringify(DEFAULT_CN_LIST));
        }
      });
    };
    init();

    return {
      modelRef,
      validateInfos,
      ...toRefs(state),
      editContractNo,
      getPreviewText,
      handleEditContractNoSuccess,
    };
  },
});
</script>

<style lang="less" scoped>
.contract-no {
  :deep(.ant-form-item) {
    margin-bottom: 16px;
  }
}
</style>
